//将ast语法树=>reader函数(拼接字符串)

//匹配{{}}双花括号
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g;


//拼接attrs属性字符串
function genProps(attrs) {
    //空字符串
    let str = '';
    //遍历 ast语法树中的属性数组
    for (let i = 0; i < attrs.length; i++) {
        //获属性对象
        let attr = attrs[i];
        //
        if (attr.name === 'style') {
            let obj = {};
            attr.value.split(';').forEach(item => {
                let [key, value] = item.split(":");
                obj[key] = value
            })
            attr.value = obj;
        }
        str += `${attr.name}:${JSON.stringify(attr.value)},`;
    }
    return `{${str.slice(0, -1)}}`;
}
//拼接chilren字符串
function genChildren(el) {
    //debugger
    //console.log(el);
    const children = el.children;
    //这里修改1
    if (children && children.length > 0) {
        return children.map(child => gen(child)).join(',');
    }
}
//拼接chilren属性中的节点
function gen(node) {
    if (node.type == 1) {
        //如果是普通元素,递归
        return generate(node)
    } else {
        //如果是文本节点
        let text = node.text;
        //匹配{{}}花括号
        if (defaultTagRE.test(text)) {
            let tokens = [];
            let match;
            let index = 0;
            let lastIndex = defaultTagRE.lastIndex = 0;
            while (match = defaultTagRE.exec(text)) {
                index = match.index;
                if (index > lastIndex) {
                    tokens.push(JSON.stringify(text.slice(lastIndex, index)))
                }
                tokens.push(`_s(${match[1].trim()})`);
                lastIndex = index + match[0].length
            }
            if (lastIndex < text.length) {
                tokens.push(JSON.stringify(text.slice(lastIndex)))
            }
            //debugger
            return `_v(${tokens.join('+')})`

        } else {
            return `_v(${JSON.stringify(text)})`
        }
    }
}
//html=>string=>reader(funciton)
export function generate(el) {
    //console.log(el);
    let children = genChildren(el)
    //拼接成reader函数参数形式的字符串
    let code = `_c('${el.tag}',${el.attrs.length ? genProps(el.attrs) : 'undefined'
        }${children ? (',' + children) : ''})`;
    //console.log(code);
    return code;
}

/*
<div id="app" a=1 b=2>
    <span style="color:red;background:red">{{name}}</span>
</div>
render(){
    return _c(
        'div',{id:'app',a:1,b:2}
        ,_c(
            'span',
            {style:{color:'red'}}
            ,_s(_v(name)),
            _c(a,{},_v('hello'))
        )
    )
}
*/